package tq.com.download;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import tq.com.systools.system.DirectHelper;

public class TQDownloadManager {
    static private String TAG = "TQDownloadManager";
    static private String baseUrl;
    static public void setBaseUrl(String pUrl){
        baseUrl = pUrl;
    }

    static String fullUrl(String path){
        return String.format("%s%s", baseUrl, path);
    }


    static private TQDownloadManager sDownloadManager = new TQDownloadManager();
    static public TQDownloadManager getDownloadManager(){
        return sDownloadManager;
    }


    private HashMap<String, TQDownloadTask> mDownloadTaskHashMap = new HashMap<>();
    private void add(String key, TQDownloadTask pTask){
        synchronized (mDownloadTaskHashMap){
            mDownloadTaskHashMap.put(key, pTask);
        }
    }
    private void cancle(String key){
        synchronized (mDownloadTaskHashMap){
            TQDownloadTask lTQDownloadTask = mDownloadTaskHashMap.get(key);
            if(lTQDownloadTask != null){
                lTQDownloadTask.cancel(true);
            }

            mDownloadTaskHashMap.remove(key);
        }
    }

    private void remove(String key){
        synchronized (mDownloadTaskHashMap){
            TQDownloadTask lTQDownloadTask = mDownloadTaskHashMap.get(key);
            if(lTQDownloadTask != null){
                lTQDownloadTask.cancel(true);
            }

            mDownloadTaskHashMap.remove(key);
        }
    }

    static public boolean checkCahce(String id, String fileType){
        String full = String.format("%s/%s%s", DirectHelper.getAppCacheDirectory(), id, fileType);

        File lFile = new File(full);
        return lFile.exists();
    }

    static public String cachePath(String id, String fileType){
        String full = String.format("%s/%s%s", DirectHelper.getAppCacheDirectory(), id, fileType);
        return full;
    }

    private static HashMap<String, String> defaultHeader = new HashMap<>();

    static public void addDefaultHeader(String k, String v){
        if(k == null || v == null) return;

        defaultHeader.put(k, v);
    }
    static public class Build implements IDownloadListener{
        private String url;
        private String id;

        private IDownloadListener mDownloadListener;
        private HashMap<String, String> header = new HashMap<>();

        private String fileType;
        private String localPath;

        private int status;

        public Build setFileId(String pId){
            id = pId;
            return this;
        }

        public Build setListener(IDownloadListener pListener){
            mDownloadListener = pListener;
            return this;
        }

        public Build setUrl(String pUrl){
            url = pUrl;
            return this;
        }
        public Build setFileType(String pFileType){
            fileType = pFileType;
            return this;
        }

        public IDownloadListener getDownloadListener(){
            return mDownloadListener;
        }

        public Build addHeader(String k, String v){
            if(k == null || v == null)return this;

            header.put(k, v);
            return this;
        }

        public String getUrl(){
            if(url != null && url.length() > 0){
                return url;
            }
            return fullUrl(id);
        }

        public HashMap<String, String> getHeader(){
            HashMap<String, String> lHashMap = new HashMap<>();
            lHashMap.putAll(lHashMap);
            lHashMap.putAll(defaultHeader);

            return lHashMap;
        }
        public void setLocalPath(String pLocalPath){
            localPath = pLocalPath;
        }

        public String getLocalPath(){
            if(localPath != null && localPath.length() > 0)
                return localPath;
            return DirectHelper.getAppCacheDirectory();
        }

        public void save(InputStream pInputStream){
            if(pInputStream == null)return;

            File dir = new File(getLocalPath());
            if(!dir.exists()){
                dir.mkdirs();
            }

            byte[] buf = new byte[2048];
            int len;
            FileOutputStream lOutputStream = null;
            File lFile1 = new File(dir, String.format("%s%s", id, fileType));
            if(lFile1.exists() && lFile1.isFile()){
                lFile1.delete();
            }

            try{
                lOutputStream = new FileOutputStream(lFile1);

                while ((len = pInputStream.read(buf)) != -1) {
                    lOutputStream.write(buf, 0, len);
                }
                lOutputStream.flush();

                localPath = lFile1.getPath();
            }catch (Exception pE){
                pE.printStackTrace();
            } finally {
                try {
                    if (lOutputStream != null) lOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(status != 0){
                lFile1.delete();
            }
        }

        public void start(){
            TQDownloadTask lTQDownloadTask = new TQDownloadTask(this);
            getDownloadManager().add(getUrl(), lTQDownloadTask);
            lTQDownloadTask.execute(getUrl());
        }

        public void cancel(){
            status = 1;
            getDownloadManager().cancle(getUrl());
        }

        public void process(long current, long total){
            Log.d(TAG, "process: ");
            if(mDownloadListener != null){
                mDownloadListener.process(current, total);
            }


        }
        public void fail(String msg){
            Log.d(TAG, "fail: ");
            if(mDownloadListener != null){
                mDownloadListener.fail(msg);
            }
            getDownloadManager().remove(getUrl());
        }
        public void success(String pFileType){
            if(mDownloadListener != null){
                mDownloadListener.success(localPath);
            }

            getDownloadManager().remove(getUrl());
        }
    }
}
